// MongoDB Sample Data Generation Script

// ==================================
// 4.1 用户模块
// ==================================

// 4.1.1 users (小程序用户 - 按要求不生成10条)
// db.users.insertOne({ ... }); // 按需添加用户

// 4.1.2 admin_users (后台管理员 - 生成指定用户)
db.admin_users.insertOne({
  _id: ObjectId(),
  username: "admin",
  password: "admin123", // 重要：生产环境需要哈希加密!
  name: "管理员",
  avatar: "https://images.unsplash.com/photo-1570295999919-56ceb5ecca61?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80",
  email: "admin@example.com",
  phone: "13800138000",
  role: "admin",
  permissions: ["read", "write", "delete", "manage_users", "manage_foods", "manage_recipes"],
  createdAt: new Date(),
  updatedAt: new Date(),
  lastLoginAt: new Date(),
  isActive: true
});
print("1 admin_users inserted.");

// ==================================
// 4.2 食物数据库模块
// ==================================

// 4.2.2 food_categories (食物分类)
const foodCategoryIds = [];
const foodCategoriesData = [
  { name: "谷物", icon: "🍚", description: "提供主要碳水化合物", order: 1, isActive: true },
  { name: "蔬菜", icon: "🥦", description: "富含维生素和纤维", order: 2, isActive: true },
  { name: "水果", icon: "🍎", description: "天然糖分和维生素来源", order: 3, isActive: true },
  { name: "肉类", icon: "🥩", description: "主要蛋白质来源", order: 4, isActive: true },
  { name: "鱼类海鲜", icon: "🐟", description: "优质蛋白和不饱和脂肪酸", order: 5, isActive: true },
  { name: "蛋奶制品", icon: "🥛", description: "钙和蛋白质来源", order: 6, isActive: true },
  { name: "豆类坚果", icon: "🥜", description: "植物蛋白和健康脂肪", order: 7, isActive: true },
  { name: "油脂", icon: "🧈", description: "提供脂肪和能量", order: 8, isActive: true },
  { name: "饮品", icon: "🥤", description: "补充水分或其他", order: 9, isActive: true },
  { name: "零食", icon: "🍫", description: "休闲食品", order: 10, isActive: true },
  { name: "调味品", icon: "🧂", description: "增加风味", order: 11, isActive: true }
];
foodCategoriesData.forEach(cat => {
  const result = db.food_categories.insertOne({
    _id: ObjectId(),
    ...cat,
  });
  foodCategoryIds.push(result.insertedId);
});
print(`${foodCategoryIds.length} food categories inserted.`);

// 4.2.1 foods (食物数据)
const foodIds = [];
const foodsData = [
  // 谷物 (示例)
  { name: "米饭", category: { _id: foodCategoryIds[0], name: "谷物" }, image: "https://images.unsplash.com/photo-1599043513900-ed6fe01d3833?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 130, nutrition: { protein: 2.7, fat: 0.3, carbohydrate: 28.2, fiber: 0.4, sugar: 0.1, sodium: 1, cholesterol: 0 }, isVerified: true, source: "USDA", createdAt: new Date(), updatedAt: new Date() },
  { name: "全麦面包", category: { _id: foodCategoryIds[0], name: "谷物" }, image: "https://images.unsplash.com/photo-1598373182133-9b46f544140a?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 265, nutrition: { protein: 13, fat: 3.4, carbohydrate: 48, fiber: 7, sugar: 5, sodium: 491, cholesterol: 0 }, isVerified: true, source: "权威机构A", createdAt: new Date(), updatedAt: new Date() },
  // 蔬菜 (示例)
  { name: "西兰花", category: { _id: foodCategoryIds[1], name: "蔬菜" }, image: "https://images.unsplash.com/photo-1587351177733-a03efcae3eb1?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 34, nutrition: { protein: 2.8, fat: 0.4, carbohydrate: 6, fiber: 2.6, sugar: 1.5, sodium: 33, cholesterol: 0 }, isVerified: true, source: "权威机构B", createdAt: new Date(), updatedAt: new Date() },
  { name: "番茄", category: { _id: foodCategoryIds[1], name: "蔬菜" }, image: "https://images.unsplash.com/photo-1582284540020-8acbe03fec79?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 18, nutrition: { protein: 0.9, fat: 0.2, carbohydrate: 3.9, fiber: 1.2, sugar: 2.6, sodium: 5, cholesterol: 0 }, isVerified: true, source: "USDA", createdAt: new Date(), updatedAt: new Date() },
  // 水果 (示例)
  { name: "苹果", category: { _id: foodCategoryIds[2], name: "水果" }, image: "https://images.unsplash.com/photo-1560806887-1e4cd0b6cbd6?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 52, nutrition: { protein: 0.3, fat: 0.2, carbohydrate: 14, fiber: 2.4, sugar: 10, sodium: 1, cholesterol: 0 }, isVerified: true, source: "权威机构C", createdAt: new Date(), updatedAt: new Date() },
  { name: "香蕉", category: { _id: foodCategoryIds[2], name: "水果" }, image: "https://images.unsplash.com/photo-1587132137056-bfbf0166836e?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 89, nutrition: { protein: 1.1, fat: 0.3, carbohydrate: 23, fiber: 2.6, sugar: 12, sodium: 1, cholesterol: 0 }, isVerified: true, source: "USDA", createdAt: new Date(), updatedAt: new Date() },
  // 肉类 (示例)
  { name: "鸡胸肉", category: { _id: foodCategoryIds[3], name: "肉类" }, image: "https://images.unsplash.com/photo-1587593810167-a84920ea0781?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 165, nutrition: { protein: 31, fat: 3.6, carbohydrate: 0, fiber: 0, sugar: 0, sodium: 74, cholesterol: 85 }, isVerified: true, source: "权威机构D", createdAt: new Date(), updatedAt: new Date() },
  { name: "牛肉", category: { _id: foodCategoryIds[3], name: "肉类" }, image: "https://images.unsplash.com/photo-1603360946369-dc9bb6258143?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 250, nutrition: { protein: 26, fat: 15, carbohydrate: 0, fiber: 0, sugar: 0, sodium: 72, cholesterol: 90 }, isVerified: true, source: "USDA", createdAt: new Date(), updatedAt: new Date() },
  // 蛋奶制品 (示例)
  { name: "鸡蛋", category: { _id: foodCategoryIds[5], name: "蛋奶制品" }, image: "https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 155, nutrition: { protein: 13, fat: 11, carbohydrate: 1.1, fiber: 0, sugar: 1.1, sodium: 124, cholesterol: 373 }, isVerified: true, source: "权威机构E", createdAt: new Date(), updatedAt: new Date() },
  { name: "牛奶", category: { _id: foodCategoryIds[5], name: "蛋奶制品" }, image: "https://images.unsplash.com/photo-1563636611-969115316451?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "毫升", calories: 42, nutrition: { protein: 3.4, fat: 1, carbohydrate: 5, fiber: 0, sugar: 5, sodium: 43, cholesterol: 5 }, isVerified: true, source: "USDA", createdAt: new Date(), updatedAt: new Date() },
   // 鱼类海鲜 (示例)
  { name: "三文鱼", category: { _id: foodCategoryIds[4], name: "鱼类海鲜" }, image: "https://images.unsplash.com/photo-1599084993091-1cb5c0721cc6?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=M3wzNjAzNTV8MHwxfHNlYXJjaHwxfHxyZWNlbnR8ZW58MHx8fHwxNjE2NzY1MTEw&ixlib=rb-1.2.1&q=80&w=400", unit: "克", calories: 208, nutrition: { protein: 20, fat: 13, carbohydrate: 0, fiber: 0, sugar: 0, sodium: 59, cholesterol: 55 }, isVerified: true, source: "权威机构F", createdAt: new Date(), updatedAt: new Date() }
];
foodsData.forEach(food => {
  // 补充完整的营养信息（示例，实际应填入真实数据）
  food.nutrition.vitamins = { A: Math.random()*100, C: Math.random()*50, D: Math.random()*10, E: Math.random()*5, K: Math.random()*20, B1: Math.random()*0.5, B2: Math.random()*0.5, B6: Math.random()*0.5, B12: Math.random()*1 };
  food.nutrition.minerals = { calcium: Math.random()*200, iron: Math.random()*5, magnesium: Math.random()*50, potassium: Math.random()*300, zinc: Math.random()*2 };

  const result = db.foods.insertOne({
    _id: ObjectId(),
    ...food,
  });
  foodIds.push(result.insertedId);
});
print(`${foodIds.length} foods inserted.`);


// 4.2.3 food_favorites (食物收藏 - 假设前两个用户收藏了部分食物)
const foodFavoritesData = [];
// 假设存在用户 ObjectId("user_1_id") 和 ObjectId("user_2_id")
const sampleUserIds = [ObjectId(), ObjectId()]; // 生成两个示例用户ID

for (let i = 0; i < 5; i++) {
  foodFavoritesData.push({ userId: sampleUserIds[0], foodId: foodIds[i], createdAt: new Date() });
}
for (let i = 5; i < 10; i++) {
  foodFavoritesData.push({ userId: sampleUserIds[1], foodId: foodIds[i], createdAt: new Date() });
}
if (foodFavoritesData.length > 0) {
    const result = db.food_favorites.insertMany(foodFavoritesData);
    print(`${result.insertedCount} food favorites inserted.`);
} else {
    print("No food favorites to insert.");
}

// 4.2.4 search_history (搜索历史 - 假设两个用户有搜索历史)
const searchHistoryData = [
  { userId: sampleUserIds[0], keyword: "鸡胸肉", type: "food", createdAt: new Date(Date.now() - 86400000 * 2) }, // 2天前
  { userId: sampleUserIds[0], keyword: "低卡食谱", type: "recipe", createdAt: new Date(Date.now() - 86400000) }, // 1天前
  { userId: sampleUserIds[0], keyword: "苹果", type: "food", createdAt: new Date() },
  { userId: sampleUserIds[1], keyword: "西兰花", type: "food", createdAt: new Date(Date.now() - 86400000 * 3) },
  { userId: sampleUserIds[1], keyword: "增肌餐", type: "recipe", createdAt: new Date(Date.now() - 86400000 * 1) },
  { userId: sampleUserIds[1], keyword: "牛奶", type: "food", createdAt: new Date() },
  { userId: sampleUserIds[0], keyword: "早餐", type: "recipe", createdAt: new Date() },
  { userId: sampleUserIds[1], keyword: "牛肉怎么做", type: "recipe", createdAt: new Date() },
  { userId: sampleUserIds[0], keyword: "香蕉", type: "food", createdAt: new Date() },
  { userId: sampleUserIds[1], keyword: "番茄炒蛋", type: "recipe", createdAt: new Date() },
];
if (searchHistoryData.length > 0) {
    const result = db.search_history.insertMany(searchHistoryData);
    print(`${result.insertedCount} search history records inserted.`);
} else {
    print("No search history to insert.");
}


// ==================================
// 4.3 饮食记录模块
// ==================================

// 4.3.1 diet_records (饮食记录)
const dietRecordsData = [];
const mealTypes = ["早餐", "午餐", "晚餐", "加餐"];
for (let i = 0; i < 10; i++) {
  const food1 = db.foods.findOne({ _id: foodIds[Math.floor(Math.random() * foodIds.length)] });
  const food2 = db.foods.findOne({ _id: foodIds[Math.floor(Math.random() * foodIds.length)] });
  if (!food1 || !food2) {
      print(`Warning: Could not find food for diet record ${i+1}. Skipping this record.`);
      continue; // 跳过此记录
  }
  const amount1 = 50 + Math.random() * 150; // 50-200g
  const amount2 = 30 + Math.random() * 100; // 30-130g
  const calories1 = (food1.calories / 100) * amount1;
  const calories2 = (food2.calories / 100) * amount2;
  const nutrition1 = {};
  const nutrition2 = {};

  // 递归计算营养成分
  const calculateNutrition = (nutritionSource, amount) => {
      const calculated = {};
      for (const key in nutritionSource) {
          if (typeof nutritionSource[key] === 'number') {
              calculated[key] = (nutritionSource[key] / 100) * amount;
          } else if (typeof nutritionSource[key] === 'object' && nutritionSource[key] !== null) {
              calculated[key] = calculateNutrition(nutritionSource[key], amount); // 递归调用
          }
      }
      return calculated;
  };

  // 递归合并营养成分
  const mergeNutrition = (nut1, nut2) => {
      const merged = {};
      const allKeys = new Set([...Object.keys(nut1), ...Object.keys(nut2)]);
      allKeys.forEach(key => {
          const val1 = nut1[key];
          const val2 = nut2[key];
          if (typeof val1 === 'number' && typeof val2 === 'number') {
              merged[key] = (val1 || 0) + (val2 || 0);
          } else if (typeof val1 === 'object' && val1 !== null && typeof val2 === 'object' && val2 !== null) {
              merged[key] = mergeNutrition(val1, val2); // 递归合并
          } else if (typeof val1 !== 'undefined') {
              merged[key] = val1; // 保留其中一个值
          } else {
              merged[key] = val2;
          }
      });
      return merged;
  };

  nutrition1 = calculateNutrition(food1.nutrition, amount1);
  nutrition2 = calculateNutrition(food2.nutrition, amount2);
  const totalNutrition = mergeNutrition(nutrition1, nutrition2);


  dietRecordsData.push({
    _id: ObjectId(),
    userId: sampleUserIds[i % 2], // 交替分配给两个用户
    mealType: mealTypes[i % 4],
    date: new Date(Date.now() - (i % 3) * 86400000), // 最近三天
    time: `${String(Math.floor(Math.random()*24)).padStart(2, '0')}:${String(Math.floor(Math.random()*60)).padStart(2, '0')}`,
    foods: [
      { food: { _id: food1._id, name: food1.name, image: food1.image, unit: food1.unit, calories: food1.calories }, amount: Math.round(amount1), unit: food1.unit, calories: Math.round(calories1), nutrition: nutrition1 },
      { food: { _id: food2._id, name: food2.name, image: food2.image, unit: food2.unit, calories: food2.calories }, amount: Math.round(amount2), unit: food2.unit, calories: Math.round(calories2), nutrition: nutrition2 }
    ],
    totalCalories: Math.round(calories1 + calories2),
    totalNutrition: totalNutrition,
    note: `今天的第${i+1}条记录示例`,
    images: [ `https://images.pexels.com/photos/1640777/pexels-photo-1640777.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500` ],
    createdAt: new Date(),
    updatedAt: new Date(),
  });
}
if (dietRecordsData.length > 0) {
    const result = db.diet_records.insertMany(dietRecordsData);
    print(`${result.insertedCount} diet records inserted.`);
} else {
    print("No diet records to insert.");
}


// ==================================
// 4.4 食谱管理模块
// ==================================

// 4.4.3 recipe_categories (食谱分类)
const recipeCategoryIds = [];
const recipeCategoriesData = [
  { name: "家常菜", icon: "🍳", description: "日常简单菜肴", order: 1, isActive: true },
  { name: "快手菜", icon: "⏱️", description: "制作时间短", order: 2, isActive: true },
  { name: "烘焙", icon: "🍞", description: "面包、蛋糕等", order: 3, isActive: true },
  { name: "汤羹", icon: "🥣", description: "各类汤品", order: 4, isActive: true },
  { name: "饮品", icon: "🍹", description: "自制饮品", order: 5, isActive: true },
  { name: "西餐", icon: "🍝", description: "西式料理", order: 6, isActive: true },
  { name: "日韩料理", icon: "🍣", description: "日式和韩式菜肴", order: 7, isActive: true },
  { name: "健身餐", icon: "💪", description: "高蛋白低脂", order: 8, isActive: true },
  { name: "宝宝辅食", icon: "👶", description: "适合婴幼儿", order: 9, isActive: true },
  { name: "节日美食", icon: "🎉", description: "特殊场合菜肴", order: 10, isActive: true }
];
recipeCategoriesData.forEach(cat => {
  const result = db.recipe_categories.insertOne({
    _id: ObjectId(),
    ...cat,
  });
  recipeCategoryIds.push(result.insertedId);
});
print(`${recipeCategoryIds.length} recipe categories inserted.`);

// 4.4.1 recipes (食谱数据)
const recipeIds = [];
const adminUser = db.admin_users.findOne({username: "admin"});
const adminUserId = adminUser ? adminUser._id : ObjectId(); // 获取管理员ID或生成新的
const sampleAuthor = { _id: adminUserId, name: adminUser ? adminUser.name : "管理员" };

const recipesData = [];
for(let i = 0; i < 10; i++) {
    const food1 = db.foods.findOne({ _id: foodIds[Math.floor(Math.random() * foodIds.length)] });
    const food2 = db.foods.findOne({ _id: foodIds[Math.floor(Math.random() * foodIds.length)] });
    const food3 = db.foods.findOne({ _id: foodIds[Math.floor(Math.random() * foodIds.length)] });
    if (!food1 || !food2 || !food3) {
        print(`Warning: Could not find food for recipe ${i+1}. Skipping this recipe.`);
        continue;
    }
    const category = db.recipe_categories.findOne({ _id: recipeCategoryIds[i % recipeCategoryIds.length]});
    if (!category) {
        print(`Warning: Could not find category for recipe ${i+1}. Skipping this recipe.`);
        continue;
    }

    recipesData.push({
        _id: ObjectId(),
        title: `示例食谱 ${i+1} - ${category.name}`,
        description: `这是一道美味的${category.name}示例食谱，简单易学。`,
        coverImage: `https://images.unsplash.com/photo-1546069901-ba9599a7e63c?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80`,
        category: { _id: category._id, name: category.name },
        difficulty: Math.floor(Math.random() * 5) + 1, // 1-5
        prepTime: 10 + Math.floor(Math.random() * 20), // 10-30 min
        cookTime: 15 + Math.floor(Math.random() * 45), // 15-60 min
        servings: Math.floor(Math.random() * 4) + 1, // 1-4 servings
        ingredients: [
            { food: { _id: food1._id, name: food1.name }, amount: Math.round(100 + Math.random() * 100), unit: food1.unit },
            { food: { _id: food2._id, name: food2.name }, amount: Math.round(50 + Math.random() * 50), unit: food2.unit },
            { food: { _id: food3._id, name: food3.name }, amount: Math.round(10 + Math.random() * 20), unit: food3.unit }
        ],
        steps: [
            { stepNumber: 1, description: "准备所有材料，清洗干净。", image: `https://images.pexels.com/photos/376464/pexels-photo-376464.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500` },
            { stepNumber: 2, description: "将食材切好备用。", image: "" },
            { stepNumber: 3, description: "按照顺序烹饪。", image: `https://images.pexels.com/photos/1099680/pexels-photo-1099680.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500` },
            { stepNumber: 4, description: "装盘即可享用。", image: "" }
        ],
        nutrition: { // 营养信息需根据配料计算，这里是示例
            calories: Math.round(300 + Math.random() * 400),
            protein: Math.round(15 + Math.random() * 20),
            fat: Math.round(10 + Math.random() * 15),
            carbohydrate: Math.round(30 + Math.random() * 40)
        },
        tags: [category.name, "示例", i % 2 == 0 ? "简单" : "营养"],
        author: sampleAuthor,
        isVerified: true,
        viewCount: Math.floor(Math.random() * 1000),
        favoriteCount: Math.floor(Math.random() * 200),
        rating: parseFloat((Math.random() * 2 + 3).toFixed(1)), // 3.0 - 5.0
        reviewCount: Math.floor(Math.random() * 50),
        createdAt: new Date(Date.now() - Math.random() * 30 * 86400000), // 最近一个月内创建
        updatedAt: new Date()
    });
}
if (recipesData.length > 0) {
    const result = db.recipes.insertMany(recipesData);
    result.insertedIds.forEach(id => recipeIds.push(id));
    print(`${result.insertedCount} recipes inserted.`);
} else {
    print("No recipes to insert.");
}


// 4.4.2 recipe_favorites (食谱收藏)
const recipeFavoritesData = [];
for (let i = 0; i < 10; i++) {
    // 确保 recipeIds 数组不为空
    if (recipeIds.length === 0) break;
    recipeFavoritesData.push({
        _id: ObjectId(),
        userId: sampleUserIds[i % 2],
        recipeId: recipeIds[Math.floor(Math.random() * recipeIds.length)],
        createdAt: new Date(Date.now() - Math.random() * 7 * 86400000) // 最近一周内收藏
    });
}
// 确保唯一性 (userId, recipeId)
const uniqueRecipeFavorites = Array.from(new Map(recipeFavoritesData.map(item => [`${item.userId}-${item.recipeId}`, item])).values());

if (uniqueRecipeFavorites.length > 0) {
    const result = db.recipe_favorites.insertMany(uniqueRecipeFavorites);
    print(`${result.insertedCount} recipe favorites inserted.`);
} else {
    print("No recipe favorites to insert.");
}

// ==================================
// 4.5 营养分析模块
// ==================================

// 4.5.1 nutrition_goals (营养目标)
const nutritionGoalsData = [];
sampleUserIds.forEach((userId, index) => {
    nutritionGoalsData.push({
        _id: ObjectId(),
        userId: userId,
        caloriesGoal: 1800 + index * 200, // 1800 or 2000
        nutritionGoals: { // 示例目标，应根据用户情况计算
            protein: 80 + index * 20, fat: 50 + index * 10, carbohydrate: 200 + index * 30,
            fiber: 25 + index * 5, sugar: 50, sodium: 1500
        },
        macroRatio: { // 示例比例
            protein: parseFloat((0.20 + index * 0.05).toFixed(2)),
            fat: 0.30,
            carbohydrate: parseFloat((0.50 - index * 0.05).toFixed(2))
        },
        createdAt: new Date(),
        updatedAt: new Date()
    });
});
// 添加更多目标...
for (let i = 0; i < 8; i++) {
     nutritionGoalsData.push({
        _id: ObjectId(),
        userId: ObjectId(), // 新的示例用户ID
        caloriesGoal: Math.round(1600 + Math.random() * 600),
        nutritionGoals: { protein: Math.round(70 + Math.random()*30), fat: Math.round(40 + Math.random()*30), carbohydrate: Math.round(180 + Math.random()*70), fiber: Math.round(20 + Math.random()*10), sugar: Math.round(50 + Math.random()*20), sodium: Math.round(1200 + Math.random()*800) },
        macroRatio: { protein: parseFloat((0.2 + Math.random()*0.1).toFixed(2)), fat: parseFloat((0.25 + Math.random()*0.1).toFixed(2)), carbohydrate: parseFloat((0.4 + Math.random()*0.1).toFixed(2)) },
        createdAt: new Date(), updatedAt: new Date()
    });
}
if (nutritionGoalsData.length > 0) {
    const result = db.nutrition_goals.insertMany(nutritionGoalsData);
    print(`${result.insertedCount} nutrition goals inserted.`);
} else {
    print("No nutrition goals to insert.");
}


// 4.5.2 nutrition_suggestions (营养建议)
const nutritionSuggestionsData = [];
const suggestionTypes = ["营养均衡", "热量控制", "蛋白质补充", "增加膳食纤维", "减少钠摄入"];
for (let i = 0; i < 10; i++) {
    // 确保 foodIds 不为空
    if (foodIds.length === 0) break;
    const relevantFood = db.foods.findOne({ _id: foodIds[Math.floor(Math.random() * foodIds.length)] });
    if (!relevantFood) continue; // 如果找不到食物，跳过

    // 从食物营养成分中随机选一个作为理由
    const nutritionKeys = Object.keys(relevantFood.nutrition || {});
    const primaryKeys = nutritionKeys.filter(k => typeof relevantFood.nutrition[k] === 'number');
    const reasonKey = primaryKeys.length > 0 ? primaryKeys[Math.floor(Math.random() * primaryKeys.length)] : '营养';

    nutritionSuggestionsData.push({
        _id: ObjectId(),
        userId: sampleUserIds[i % 2],
        type: suggestionTypes[i % suggestionTypes.length],
        content: `建议您关注${suggestionTypes[i % suggestionTypes.length]}，可以尝试多吃 ${relevantFood.name}。`,
        relevantFoods: [{
            foodId: relevantFood._id,
            reason: `富含${reasonKey}`
        }],
        createdAt: new Date(Date.now() - Math.random() * 5 * 86400000), // 最近5天
        isRead: Math.random() > 0.5 // 随机已读/未读
    });
}
if (nutritionSuggestionsData.length > 0) {
    const result = db.nutrition_suggestions.insertMany(nutritionSuggestionsData);
    print(`${result.insertedCount} nutrition suggestions inserted.`);
} else {
    print("No nutrition suggestions to insert.");
}


// ==================================
// 4.6 系统管理模块
// ==================================

// 4.6.1 system_configs (系统配置)
const systemConfigsData = [
  { _id: ObjectId(), key: "APP_NAME", value: "饮食营养管理", category: "General", description: "小程序名称", isSystem: true, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "DEFAULT_PAGE_SIZE", value: 20, category: "API", description: "列表默认分页大小", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "MAX_IMAGE_UPLOAD_SIZE_MB", value: 5, category: "Upload", description: "最大图片上传大小(MB)", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "CACHE_EXPIRATION_SECONDS", value: 3600, category: "Cache", description: "默认缓存过期时间(秒)", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "JWT_SECRET", value: "your_strong_jwt_secret_here", category: "Security", description: "JWT签名密钥", isSystem: true, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "ENABLE_RECIPE_UPLOAD", value: true, category: "Feature", description: "是否允许用户上传食谱", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "ADMIN_EMAIL", value: "admin@example.com", category: "Notification", description: "管理员接收通知邮箱", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "POINTS_PER_RECORD", value: 5, category: "Points", description: "每次记录饮食获取积分", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "API_RATE_LIMIT_PER_MINUTE", value: 100, category: "API", description: "用户每分钟API请求限制", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "FOOD_DATA_SOURCE_PRIORITY", value: ["USDA", "权威机构A", "UserSubmitted"], category: "Data", description: "食物数据来源优先级", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId },
  { _id: ObjectId(), key: "MAINTENANCE_MODE", value: false, category: "General", description: "系统维护模式开关", isSystem: false, isActive: true, createdAt: new Date(), updatedAt: new Date(), createdBy: adminUserId, updatedBy: adminUserId }
];
if (systemConfigsData.length > 0) {
    const result = db.system_configs.insertMany(systemConfigsData);
    print(`${result.insertedCount} system configs inserted.`);
} else {
    print("No system configs to insert.");
}

// 4.6.2 user_activity_logs (用户活动日志)
const userActivityLogsData = [];
const actionTypes = ["login", "view_food", "add_diet_record", "search", "update_profile", "view_recipe", "add_favorite", "logout"];
const modules = ["user", "food", "diet_record", "search", "recipe", "favorite"];
for (let i = 0; i < 20; i++) { // 生成20条日志
    const isSuccess = Math.random() > 0.1; // 90%成功率
    const action = actionTypes[i % actionTypes.length];
    const module = modules[i % modules.length];
    let targetObjectId;
    if (action.includes("food") && foodIds.length > 0) targetObjectId = foodIds[Math.floor(Math.random()*foodIds.length)];
    else if (action.includes("recipe") && recipeIds.length > 0) targetObjectId = recipeIds[Math.floor(Math.random()*recipeIds.length)];
    else targetObjectId = ObjectId(); // 其他操作随机ID

    userActivityLogsData.push({
        _id: ObjectId(),
        userId: i % 5 === 0 ? adminUserId : sampleUserIds[i % 2], // 部分管理员日志，部分用户日志
        userType: i % 5 === 0 ? "admin" : "user",
        actionType: action,
        module: module,
        details: {
            object: targetObjectId,
            description: `执行 ${action} 操作 on ${module}`,
            // oldValue: isSuccess && action.includes("update") ? { someField: "old" } : undefined, // 按需添加
            // newValue: isSuccess && action.includes("update") ? { someField: "new" } : undefined, // 按需添加
        },
        ipAddress: `192.168.1.${Math.floor(Math.random() * 254) + 1}`,
        userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36",
        deviceInfo: {
            platform: "wechat", // 假设是小程序
            model: "iPhone 13",
            system: "iOS 15"
        },
        status: isSuccess ? "success" : "failed",
        errorMessage: isSuccess ? undefined : "操作失败，原因：示例错误信息",
        createdAt: new Date(Date.now() - Math.random() * 2 * 86400000) // 最近两天
    });
}
if (userActivityLogsData.length > 0) {
    const result = db.user_activity_logs.insertMany(userActivityLogsData);
    print(`${result.insertedCount} user activity logs inserted.`);
} else {
    print("No user activity logs to insert.");
}

// 4.6.3 statistics_cache (统计数据缓存)
const statisticsCacheData = [];
const cacheTypes = ["daily", "weekly", "monthly"];
const statModules = ["users", "diet_records", "recipes"];
for (let i = 0; i < 10; i++) {
    const module = statModules[i % statModules.length];
    const type = cacheTypes[i % cacheTypes.length];
    const endDate = new Date();
    let startDate;
    if(type === 'daily') startDate = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
    else if(type === 'weekly') {
        const dayOfWeek = endDate.getDay(); // 0 for Sunday, 1 for Monday, etc.
        startDate = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)); // Adjust to start on Monday (or Sunday if preferred)
    }
    else startDate = new Date(endDate.getFullYear(), endDate.getMonth(), 1);

    statisticsCacheData.push({
        _id: ObjectId(),
        cacheKey: `${module}_${type}_${startDate.toISOString().split('T')[0]}`,
        cacheType: type,
        module: module,
        data: {
            summary: { total: Math.floor(Math.random()*1000), active: Math.floor(Math.random()*500) },
            details: [
                { key: "cat1", value: Math.floor(Math.random()*100), label: "分类1" },
                { key: "cat2", value: Math.floor(Math.random()*200), label: "分类2" },
            ],
            chart: {
                labels: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"].slice(0, type === 'daily' ? 1 : (type === 'weekly' ? 7 : 30)), // Adjust labels based on type
                values: Array.from({length: type === 'daily' ? 1 : (type === 'weekly' ? 7 : 30)}, () => Math.floor(Math.random()*50))
            }
        },
        startDate: startDate,
        endDate: endDate,
        createdAt: new Date(),
        expireAt: new Date(Date.now() + (type === 'daily' ? 86400 * 1000 : type === 'weekly' ? 7 * 86400 * 1000 : 30 * 86400 * 1000)) // 设置过期时间
    });
}
// 确保 cacheKey 唯一
const uniqueStatsCache = Array.from(new Map(statisticsCacheData.map(item => [item.cacheKey, item])).values());

if (uniqueStatsCache.length > 0) {
    const result = db.statistics_cache.insertMany(uniqueStatsCache);
    print(`${result.insertedCount} statistics cache records inserted.`);
} else {
    print("No statistics cache records to insert.");
}

print("Sample data generation finished."); 